<template>
  <div>
    <el-form ref="form" :model="form" :rules="formRules" label-width="100px">
      <el-form-item prop="name" label="用户姓名">
        <el-input v-model="form.name" placeholder="请输入用户姓名" />
      </el-form-item>
      <el-form-item prop="mobile" label="用户手机号">
        <el-input v-model="form.mobile" placeholder="请输入用户手机号" />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" type="password" placeholder="请输入用户密码" />
      </el-form-item>
      <el-form-item prop="roles" label="角色">
        <RoleSelect v-model="form.roles" />
      </el-form-item>
      <el-form-item prop="area" label="省份">
        <AreaSelect v-model="form.area" item="id" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { create } from '../../../api/user'
export default {
  components: {
    RoleSelect: () => import('./components/RoleSelect'),
    AreaSelect: () => import('@/components/AreaSelect')
  },
  data() {
    return {
      formRules: {
        roles: [
          { required: true, message: '必须选择角色', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '必须填写名字', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '必须填写手机号', trigger: 'blur' },
          { max: 11, min: 11, message: '手机号长度不合法', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '必须填写密码', trigger: 'blur' }
        ]
      },
      form: {
        roles: [],
        name: '',
        password: '',
        area: 0,
        mobile: ''
      }
    }
  },
  methods: {
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          create(this.form).then(() => {
            this.$message.success('保存成功')
            this.$router.push({
              name: 'user-index'
            })
          })
        } else {
          console.log('fail')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
